#include "uart.h"

int16_t ttyS0FD; //ttyS0 fd

int16_t ttyS1FD; //ttyS1 fd

int16_t ttyUSBFD; //ttyS1 fd

int16_t USBHIDFD; //USBHID模块 FD

//open ttySx dev
int16_t OpenUart(const char *devStr, int16_t *fd)
{
   // *fd = open(devStr, O_RDWR | O_NOCTTY | O_NDELAY);
    *fd = open(devStr, O_RDWR | O_NOCTTY );
    if((*fd) <0)
    {
        printf("Error %d from open: %s\n", errno, strerror(errno));
        return 0;
    }
    return (*fd);
}

/* 115200, 8, N, 1 */
int16_t InitUart(int16_t fd, speed_t speed)
{
    // 读取现有设置
    struct termios tty;
    if(tcgetattr(fd, &tty) != 0) 
    {
        printf("Error %i from tcgetattr: %s\n", errno, strerror(errno));
    }
    tty.c_cflag &= ~PARENB; // Clear parity bit, disabling parity (most common)
    tty.c_cflag &= ~CSTOPB; // Clear stop field, only one stop bit used in communication
    tty.c_cflag &= ~CSIZE; // Clear all the size bits, then use one of the statements below
    tty.c_cflag |= CS8; // 8 bits per byte (most common)
    tty.c_cflag |= CREAD | CLOCAL; // Turn on READ & ignore ctrl lines (CLOCAL = 1)
    //tty.c_cflag &= ~CRTSCTS; // Disable RTS/CTS hardware flow control (most common)
    tty.c_lflag &= ~ICANON;//disable 规范模式
    tty.c_lflag &= ~ECHO; // Disable echo
    tty.c_lflag &= ~ISIG; // Disable interpretation of INTR, QUIT and SUSP
    tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL);
    tty.c_oflag &= ~OPOST; // Prevent special interpretation of output bytes (e.g. newline chars)
    tty.c_oflag &= ~ONLCR; // Prevent conversion of newline to carriage return/line feed
    tty.c_cc[VTIME] = 0;    // Wait for up to 1s (0 deciseconds), returning as soon as any data is received.
    tty.c_cc[VMIN] = 1;
    // Set in/out baud rate to be 9600
    cfsetispeed(&tty, speed); //set input
    cfsetospeed(&tty, speed); //set output
    // 保存串口的配置
    if (tcsetattr(fd, TCSANOW, &tty) != 0) 
    {
        printf("Error %i from tcsetattr: %s\n", errno, strerror(errno));
    } 
    return 0;
}


